package com.orchard.orchardfarmmanagementsystem.controller;


import com.orchard.orchardfarmmanagementsystem.entity.OrchardInfo;
import com.orchard.orchardfarmmanagementsystem.service.OrchardInfoService;
import com.orchard.orchardfarmmanagementsystem.utils.Result;
import lombok.extern.java.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/api")
public class OrchardInfoController {

    @Autowired
    private OrchardInfoService orchardInfoService;

    // 定义 Logger 实例
    private static final Logger logger = LoggerFactory.getLogger(OrchardInfoController.class);

    @GetMapping("/orchards")
    @PreAuthorize("hasAuthority('PERM_READ_DATA')")
    public Result<List<OrchardInfo>> getOrchardinfo(){
        try{
            List<OrchardInfo> orchardInfo = orchardInfoService.getAllorchardinfo();
            return Result.success("获取果园信息成功",orchardInfo);
        }catch (Exception e){
            return Result.error(50001,"获取果园信息失败");

        }
    }

    @PostMapping("/orchards")
    @PreAuthorize("hasAuthority('PERM_ADMIN_DASHBOARD')")
    public Result<OrchardInfo> createOrchard(@RequestBody OrchardInfo orchardInfo) {
        try {
            OrchardInfo createdOrchard = orchardInfoService.createOrchard(orchardInfo);
            return Result.success("创建果园成功", createdOrchard);
        } catch (Exception e) {
            // 记录异常日志（建议在生产环境中添加）
            logger.error("创建果园失败", e);
            return Result.error(50001, "创建果园失败");
        }
    }

    @PutMapping("/orchards/{id}")
    @PreAuthorize("hasAuthority('PERM_ADMIN_DASHBOARD')")
    public Result<OrchardInfo> updateOrchard(@PathVariable Long id, @RequestBody OrchardInfo orchardInfo) {
        try {
            OrchardInfo updatedOrchard = orchardInfoService.updateOrchard(id, orchardInfo);
            if (updatedOrchard == null) {
                return Result.error(404, "未找到指定的果园信息");
            }
            return Result.success("更新果园成功", updatedOrchard);
        } catch (Exception e) {
            // 记录异常日志（建议在生产环境中添加）
            logger.error("更新果园失败", e);
            return Result.error(50001, "更新果园失败");
        }
    }

    @DeleteMapping("/orchards/{id}")
    @PreAuthorize("hasAuthority('PERM_ADMIN_DASHBOARD')")
    public Result deleteOrchard(@PathVariable Long id) {
        try {
            return orchardInfoService.deleteOrchardById(id);
        } catch (Exception e) {
            // 记录异常日志（建议在生产环境中添加）
            logger.error("删除果园失败", e);
            return Result.error(50001, "删除果园失败");
        }
    }


}
